// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.appengine.preferencessync.internal.network;

import com.google.appengine.preferencessync.adapter.AbstractSyncablePrefsService.RequestProcessor;
import com.google.appengine.preferencessync.adapter.AbstractSyncablePrefsService.SyncResponse;
import com.google.appengine.preferencessync.internal.InternalSyncException;
import com.google.appengine.preferencessync.internal.InternalSyncException.ExceptionType;
import com.google.appengine.syncserver.shared.HttpParameterDefinitions.ClientRequest;

import android.util.Log;

/**
 * Utilities to send requests.
 * TODO(chintanraoh): Throw appropriate exceptions here.
 */
public class HttpUtils {

  /**
   * Send a request to the server.
   *
   * @param url
   * @param requestType
   * @param payload
   * @return Return the server response. Returns null when if the request fails.
   * @throws InternalSyncException
   */
  public static String sendRequest(
      RequestProcessor requestProcessor, String url, ClientRequest requestType, String payload)
      throws InternalSyncException {

    SyncResponse response;
    try {
      response = requestProcessor.getResponse(url, requestType.name(), payload);
    } catch (Exception e) {
      throw new InternalSyncException(
          e, ExceptionType.INTERNAL_EXCEPTION, e.getMessage(), Log.ERROR);
    }
    if (response.hasError()) {
      throw new InternalSyncException(ExceptionType.INTERNAL_EXCEPTION,
          "Internal server error", Log.DEBUG);
    }
    if (response.hasConflict()) {
      throw new InternalSyncException(ExceptionType.INTERNAL_HTTP_STATUS_CONFLICT,
          "Internal server conflict", Log.DEBUG);
    }
    return response.getResponseStr();
  }
}
